package com.woniu.qqmaster.utils;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.security.GeneralSecurityException;
import java.util.Properties;

/**
 * @Author dlb
 * @Date 2022/12/28 16:30
 */
public class SendEmailUtil {
    public static void main(String[] args) throws GeneralSecurityException, MessagingException {
        /***********************1、注册服务信息***********************************/

        Properties props = new Properties();
        // 开启debug调试
        props.setProperty("mail.debug", "true");
        // 发送服务器需要身份验证
        props.setProperty("mail.smtp.auth", "true");
        // 设置邮件服务器主机名
        props.setProperty("mail.host", "smtp.qq.com");
        // 发送邮件协议名称
        props.setProperty("mail.transport.protocol", "smtp");

        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);

        // 根据propertise创建会话
        Session session = Session.getInstance(props);

        /***********************2、创建消息对象***********************************/


        // TODO
        // 创建 Message 对象，代表一封邮件
        Message msg = new MimeMessage(session);
        // 定义邮件标题
        msg.setSubject("I LOVE YOU");
        // 来源
        msg.setFrom(new InternetAddress("1423479363@qq.com"));


        // 创建一个节点，用于描述图片
        MimeBodyPart image = new MimeBodyPart();
        DataSource dataSource = new FileDataSource("love.jpg"); //文件
        DataHandler handler = new DataHandler(dataSource);
        image.setDataHandler(handler);
        //     public void setContentID(String cid)
        image.setContentID("pic");

        MimeBodyPart text = new MimeBodyPart();
        text.setContent("<h1> 你好呀 出去玩吗？ </h1><img src='cid:pic' style='height: 100px'></img>","text/html;charset=UTF-8");

        MimeMultipart root = new MimeMultipart();
        root.addBodyPart(text);
        root.addBodyPart(image);

        msg.setContent(root);

        /***********************3、开启会话传输***********************************/

        // 开始会话传输
        Transport transport = session.getTransport();
        // 连接邮箱   加入自己（发送方）授权码
        transport.connect("smtp.qq.com", "1423479363@qq.com", "dkvgfqkkfwpnjbhi");

        // 给目标邮箱发送邮件
        transport.sendMessage(msg, new Address[] { new InternetAddress("1423479363@qq.com") });
        transport.close();

    }
}
